package com.itcv.spring.security.demo.authentication.jdbc;

import com.itcv.spring.security.demo.dao.SysRoleDao;
import com.itcv.spring.security.demo.dao.UserDao;
import com.itcv.spring.security.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class CustomJdbcUserDetailsService implements UserDetailsService {


    private SysRoleDao roleDao;

    private UserService userService;

    /**
     * zhangsan   123456
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.itcv.spring.security.demo.model.User paramUser = new com.itcv.spring.security.demo.model.User();
        paramUser.setName(username);
        List<com.itcv.spring.security.demo.model.User> userList = null;
        com.itcv.spring.security.demo.model.User sysUser = null;
        try {
            userList = userService.getUserListByParam(paramUser);
            if(null != userList && userList.size()>0){
                sysUser = userList.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        User.UserBuilder builder = User.builder()
                .username(sysUser.getUsername())
                .password(sysUser.getPassword());
        List<String> roles =  roleDao.listRoleCodeByUserId(sysUser.getId());
        builder.roles(roles == null ? new String[] {} : roles.toArray(new String[] {}));

        return builder.build();
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public SysRoleDao getRoleDao() {
        return roleDao;
    }

    public void setRoleDao(SysRoleDao roleDao) {
        this.roleDao = roleDao;
    }
}
